const std = @import("std");
const jetzig = @import("jetzig");
const article_service = @import("../service/article_service.zig");
const article_model = @import("../model/article.zig");

/// 归档页
pub fn index(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    var root = try data.object();

    const archives = try article_service.getArchiveArticles();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var year_list = std.ArrayList(u32).init(allocator);
    defer year_list.deinit();
    for (archives) |archive| {
        const created_year = try std.fmt.parseInt(u32, archive.created_at[0..4], 10);
        if (!contains(created_year, year_list.items)) {
            try year_list.append(created_year);
        }
    }

    var archive_array = try data.array();

    for (year_list.items) |year| {
        var articles = std.ArrayList(article_model.ArchiveArticle).init(allocator);
        defer articles.deinit();

        for (archives) |archive| {
            const created_year = try std.fmt.parseInt(u32, archive.created_at[0..4], 10);
            if (created_year == year) {
                try articles.append(archive);
            }
        }

        var item_obj = try data.object();
        var arts_array = try data.array();
        for (articles.items) |article| {
            var art_obj = try data.object();
            try art_obj.put("id", data.integer(article.id));
            try art_obj.put("title", data.string(article.title));
            try art_obj.put("cate_name", data.string(article.cate_name));
            try art_obj.put("created_at", data.string(article.created_at));

            try arts_array.append(art_obj);
        }
        try item_obj.put("year", data.integer(year));
        try item_obj.put("articles", arts_array);

        try archive_array.append(item_obj);
    }
    try root.put("archives", archive_array);

    return req.render(.ok);
}

/// 判断slice中是否包含某元素
pub fn contains(element: u32, slice: []u32) bool {
    for (slice) |item| {
        if (item == element) {
            return true;
        }
    }
    return false;
}
